<template>
  <div class="login-container">
    <div class="login-bg"></div>
    <div class="login-bg-mask"></div>
    <div class="login-box">
      <h3 class="title">
        <a href="javascript:void(0);" class="logo"></a>
        零食小铺
      </h3>
      <el-form
        :model="loginForm"
        status-icon
        :rules="loginRules"
        ref="loginForm"
        class="login-form"
      >
        <el-form-item prop="account">
          <el-input
            type="text"
            v-model="loginForm.account"
            placeholder="用户名 / 手机号"
            autocomplete="off"
          ></el-input>
        </el-form-item>
        <el-form-item prop="pwd">
          <el-input type="password" v-model="loginForm.pwd" placeholder="账号密码" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item class="btn-group">
          <el-button
            type="primary"
            @click="loginEvent()"
            :loading="isLogin"
          >{{isLogin?'正在登录...':'登录'}}</el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script>
import store from "@/store";
import { mapActions } from "vuex";
export default {
  data() {
    //定义一个验证账号规则
    const validateAccount = (rule, value, callback) => {
      //rule 验证规则， value 值 ，callback回调
      if (!value) {
        callback(new Error("登录账号不能为空！"));
      } else if (value.length < 4 || value.length > 16) {
        callback(new Error("登录账号长度必须是在5-16之间!"));
      } else {
        callback(); //验证通过
      }
    };
    //定义一个验证密码规则
    const validatePwd = (rule, value, callback) => {
      if (!value) {
        callback(new Error("请输入登录的账号密码！"));
      } else if (value.length < 6 || value.length > 18) {
        callback(new Error("密码长度必须是6-18个字符!"));
      } else {
        callback();
      }
    };

    return {
      isLogin: false,
      loginForm: {
        account: "",
        pwd: ""
      },
      loginRules: {
        //登录验证规则
        account: [{ validator: validateAccount, trigger: "blur" }],
        pwd: [{ validator: validatePwd, trigger: "blur" }]
      },
    };
  },
  methods: {
    ...mapActions("user", ["login"]),
    loginEvent() {
      //先触发表单验证，如果验证通过，才发起登录请求
      this.$refs.loginForm.validate(valid => {
        // console.log('登录！',this.$refs.loginForm);
        if (valid) {
          this.isLogin = true;
          this.loading = true;
          //向服务端发送登录请求
          this.$http.login(this.loginForm).then(res => {
            //调用element中的一个提示组件 - 登录成功提示
            if (res) {
              this.$message({
                type: "success",
                message: "登录成功！"
              });
              //将登录成功后返回的用户信息数据存储到vuex 和 本地存储 (注意：当用户信息存储完毕之后，其实应该跳转到登录前或者后台的主页面)
              this.login(res.data.data).then(() => {
                //跳转到登录主页
                let redirectTo = this.$route.query.redirect || "/"; //获取拦截之前的页面路由地址，如果没有则返回首页
                // console.log(redirectTo);
                this.$router.push({
                  path: redirectTo
                });
              });
            }
            this.isLogin = false;
          });
        }
      });
    }
  },
  beforeRouteEnter(to, from, next) {
    // console.log('即将进入登录组件',store);
    //判断是否已经登录 ，如果已经登录状态，应该跳转到后台首页
    // console.log(this);
    if (store.state.user.info.access_token != "") {
      next({
        path: "/"
      });
    }else{
      next();
    }
  }
};
</script>

<style scoped lang="less">
.login-container {
  position: relative;
  height: 100vh;
  .login-bg {
    position: absolute;
    width: 100%;
    height: 100%;
    background: url(./bg.jpg) no-repeat 0 0 ~"/" cover fixed;
    filter: blur(2px);
  }
  .login-bg-mask {
    position: absolute;
    width: 100%;
    height: 100%;
    background-color: rgba(0, 0, 0, 0.15);
  }
  .login-box {
    position: absolute;
    left: 50%;
    top: 50%;
    transform: translate(-50%, -50%);
    width: 340px;
    padding: 40px 30px;
    background: #fff;
    border-radius: 5px;
    box-shadow: 0 0 0 14px rgba(255, 255, 255, 0.4);

    .title {
      font-weight: 400;
      font-size: 22px;
      color: #666;
      text-align: center;
      line-height: 50px;
      margin-bottom: 30px;
      letter-spacing: 2px;
      .logo {
        display: block;
        margin: 0 auto;
        width: 50px;
        height: 50px;
        background: url(../../assets/images/logo.png) no-repeat center ~"/" 50px
          auto;
        opacity: 0.7;
        transition: all 0.35s;
        &:hover {
          opacity: 1;
        }
      }
    }

    .btn-group {
      .el-button {
        display: block;
        width: 100%;
      }
    }
  }
}
</style>
